//
//  WSJPopview.m
//  BaxTer
//
//  Created by wsj2015 on 16/9/1.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "WSJPopview.h"
#import "KLCPopup.h"
#import "IQKeyboardManager.h"
#import "LDProgressView.h"
#import "BTRatingView.h"
#import "CKHttpCommunicate.h"
#import "HELPDFfileCacheTool.h"

@interface WSJPopview ()

@property (nonatomic,  strong) KLCPopup *pop;



@property (nonatomic,  strong) UILabel *titleL;


@property (nonatomic,  strong) LDProgressView *progressView;

@property (nonatomic,  strong) UIButton *canBtn;

@property (nonatomic,  strong) NSURLSessionDownloadTask *downTask;

@property (nonatomic,  strong) NSString *urlStr;
@property (nonatomic,  strong) HELCourseContentModel *pdfModel;




@end
@implementation WSJPopview

+ (instancetype)sharedWsjPopView{
    
    return [[WSJPopview alloc] init];
    
    
    
}







- (void)showRatingView:(BOOL)isAbleRate withHelpScore:(CGFloat)helpScore  withDoneBlock:(void(^)(CGFloat help_score,NSString * commet))doneBlock{
    
    CGFloat f = kScreenFactor;
 
    BTRatingView *ratingView = [BTRatingView ratingView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    ratingView.frame =CGRectMake(0, 0, 300 * f, 325);

    KLCPopup *pop =  [KLCPopup popupWithContentView:ratingView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
      [IQKeyboardManager sharedManager].enable = NO;
    
    pop.didFinishDismissingCompletion = ^(){
        [IQKeyboardManager sharedManager].enable = YES;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    };
    self.pop = pop;
    [pop show];
    __weak typeof(ratingView) weakR = ratingView;
    if (isAbleRate == YES) {
        ratingView.confirmBlock = ^(CGFloat h,NSString * c){
            
            doneBlock(h,c);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
        
        
    }else{
        
        ratingView.helpNess.value = helpScore;
       
        ratingView.ableToRate = NO;
        
        ratingView.confirmBlock = ^(CGFloat h,NSString * c){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
        
    }
    
}

- (void)keyboardWillShow:(NSNotification *)info
{
  
    
    CGRect frame = self.pop.frame;
    frame.origin.y = -120;
    [UIView animateWithDuration:.35 delay:0 usingSpringWithDamping:.6 initialSpringVelocity:.6 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.pop.frame = frame;
    } completion:nil];
    
}
- (void)keyboardWillHide:(NSNotification *)info
{
   
    
    CGRect frame = self.pop.frame;
    frame.origin.y = 0;
    [UIView animateWithDuration:.35 delay:0 usingSpringWithDamping:.6 initialSpringVelocity:.6 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.pop.frame = frame;
    } completion:nil];
 
}



- (void)btnClick{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    self.titleL.text  =@"取消中...";
    self.progress = 0.0;
    [self.downTask cancel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.pop dismiss:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self clear];
        });
    });
    
    
}
- (void)clear{
    
  
    //    [self.progressView removeObserver:self forKeyPath:@"progress"];
    
    for (UIView *v in self.pop.subviews) {
        [v removeFromSuperview];
    }
    
    self.pop = nil;
    
    
}
- (instancetype)showDownLoadWithCourse:(HELCourseContentModel *)course{
   
    
    self.pdfModel = course;
    UIView *view =[UIView new];
    CGFloat f = kScreenFactor;
    view.frame = CGRectMake(0, 0, 268 * f, f *130);
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    
    CGFloat w = 268 * f;
    UILabel *label = [UILabel new];
    
    label.font = [UIFont systemFontOfSize:17];
    label.text = @"正在下载中...";
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    
    self.titleL = label;
    
    LDProgressView * progressView = [[LDProgressView alloc] initWithFrame:CGRectMake(0, 0 + 10 *f, w-40, 22)];
    progressView.center = view.center;
    
    label.frame = CGRectMake(0, CGRectGetMinY(progressView.frame) -12 -20, w, 20);
    
    progressView.color = [UIColor greenColor];
    progressView.flat = @YES;
    progressView.progress = 0.0;
    progressView.animate = @YES;
    progressView.showText = @YES;
    //    progressView.showStroke = @YES;
    progressView.progressInset = @0;
    progressView.showBackground = @YES;
    //    progressView.backgroundColor = [UIColor lightGrayColor];
    //    progressView.outerStrokeWidth = @1;
    progressView.type = LDProgressGradient;
    //    progressView.showTextAlways = @YES;
    //    progressView.textColor = [UIColor whiteColor];
    //    progressView.textAlignment =@(0);
    [view addSubview:progressView];
    self.progressView = progressView;
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    //    btn.center = CGPointMake(view.center.x, );
    CGFloat btnw = 120 *f;
    btn.frame = CGRectMake((w - btnw) /2, CGRectGetMaxY(progressView.frame) + 10 * f, 120 *f, 33);
    [btn setBackgroundColor:kMainColor];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    [view addSubview:btn];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius = 10;
    btn.layer.masksToBounds = YES;
    self.canBtn = btn;
    self.pop =  [KLCPopup popupWithContentView:view showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOut maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    [self.pop show];
    [self.pop setValue:@(1) forKey:@"isShowing"];
    weakSelf_define;
    self.pop.didFinishDismissingCompletion = ^(){
        
        [weakSelf clear];
    };
    
    [self startDownload];
    
    
    
    return self;
    
}
- (void)startDownload{
    
    weakSelf_define;
    __block BOOL isFail = 0;
//   http://192.168.3.82:8080/nurseLearning-mobile/mobile/course/operation/readFile/pload/2017/2017-03-02/49a7ee32-073d-4c14-925c-994acfe4732e.pdf
//    upload/2017/2017-03-02/49a7ee32-073d-4c14-925c-994acfe4732e.pdf
//    /mobile/course/operation/readFile/{folder}/{year}/{date}/{id}.{type}
    
    NSString *url =[NSString stringWithFormat:@"%@/mobile/course/operation/readFile/%@",[HELNetworkManager sharedMg].bathURL,self.pdfModel.fileUrl];
    
    self.downTask = [CKHttpCommunicate createDownloadFileWithURLString:url downloadFileProgress:^(NSProgress *progress) {
        if (isFail == 1) {
            return ;
        }
        //       __block typeof(weakSelf) self = weakSelf;
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            self.progress = progress.fractionCompleted;
            
            //            hud.label.text = [NSString stringWithFormat:@"已下载%.f%%",progress.fractionCompleted *100];
        });
        
        //        WSJLog(@"---%f,%f",progress,progress.completedUnitCount);
        
    } setupFilePath:^NSURL *(NSURLResponse *response) {
        
      
        return [NSURL fileURLWithPath: [HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.pdfModel.fileName isMp4:NO]];
        
    } downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (error) {
                isFail = 1;
                cwqHudRequestError(error.localizedDescription);
                
                //下载出错  移除可能的文件
                [HELPDFfileCacheTool removePdfFileWithPdfNames:@[weakSelf.pdfModel]];
                [weakSelf.pop dismiss:YES];
                
                if (weakSelf.failBlock) {
                    weakSelf.failBlock();
                }
                return ;
            }
            weakSelf.titleL.text  =@"下载完成";
            weakSelf.progressView.progress = 1;
            if (weakSelf.doneBlock) {
                weakSelf.doneBlock();
            }
//            //更新数据库
//            [[RLMCourseManager manager] creatOrUpdateCourse:weakSelf.vedioModel];
            [weakSelf.canBtn setTitle:@"确定" forState:UIControlStateNormal];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.pop dismiss:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self clear];
                });
            });
            
            
            
            
        });
        
    }];
    
}
- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    self.progressView.progress = progress;
}



@end
